﻿using Microsoft.Extensions.Logging;
using QDWK.Class;
using Quartz;
using System.Collections.Concurrent;

namespace QDWK.Scheduler
{
    public class DataQueryJob : IJob
    {
        private readonly ILogger<DataQueryJob> _logger;
        private readonly CQdwk _cQdwk;
        private  readonly CZjzy _cZjzy;
        private static ConcurrentDictionary<string,MesData> MesDataCache = new();
        

        public DataQueryJob(ILogger<DataQueryJob> logger, CQdwk cQdwk, CZjzy cZjzy)
        {
            _logger = logger;
            _cQdwk = cQdwk;
            _cZjzy = cZjzy;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            int errorCount = 0;
            _logger.LogInformation("任务开始执行");

            try
            {
                _logger.LogInformation("开始读取Excel");
                var mesData = _cQdwk.ReadExcel("mesdata.xlsx");
                _logger.LogInformation("读取Excel完成");
                _logger.LogInformation("开始获取Session");
                var ret = await _cQdwk.GetSession();
                if (ret)
                {
                    _logger.LogInformation("获取Session完成");                    
                }
                else
                {
                    _logger.LogError("获取Session失败");
                    _logger.LogInformation("获取Session失败");
                    return;
                }

                await Task.Delay(1000);
                _logger.LogInformation("开始获取库存");
                var lstMesData = new List<MesData>();

                foreach (var item in mesData)
                {
                    var result = await _cQdwk.GetData(item.VendorMaterialCode);                    
                    if(result != null)
                    {
                        item.stock = result.stock;
                        item.unit = result.unit;
                    }
                    else
                    {
                        item.stock = "0";
                        errorCount++;
                    }   

                    if (!string.IsNullOrEmpty(item.materialCode))
                    {
                        if (!MesDataCache.TryGetValue(item.materialCode, out var data))
                        {
                            MesDataCache.TryAdd(item.materialCode, item);
                            lstMesData.Add(item);
                        }
                        else
                        {
                            if (data.stock != item.stock)
                            {
                                data.stock = item.stock;
                                lstMesData.Add(item);
                            }
                        }
                    }

                    await Task.Delay(100);
                }
                _logger.LogInformation($"获取库存完成,异常数量：{errorCount}");

                //写入Excel
                ret = await _cQdwk.WriteExcel(mesData);
                if (ret)
                {
                    _logger.LogInformation("写入Excel完成");
                }
                else
                {
                    _logger.LogError("写入Excel失败");
                    _logger.LogInformation("写入Excel失败");
                }

                var uploadDate = new List<VendorStock>();
                foreach(var item in lstMesData)
                {
                    var data = new VendorStock
                    {
                        vendorCode = item.vendorCode,
                        materialCode = item.materialCode,
                        stock = item.stock,
                        stock_date = item.stock_date,
                        deliveryPeriod = item.deliveryPeriod,
                        unit = item.unit,
                        remark1 = item.remark1,
                        remark2 = item.remark2,
                        remark3 = item.remark3,
                        remark4 = item.remark4,
                        remark5 = item.remark5,
                        remark6 = item.remark6,
                        remark7 = item.remark7,
                        remark8 = item.remark8
                    };
                    uploadDate.Add(data);
                }


                int batchSize = 100;
                _logger.LogInformation($"开始上传数据，共 {uploadDate.Count} 条");
                for (int pageIndex = 0; pageIndex * batchSize < uploadDate.Count; pageIndex++)
                {
                    // 获取当前批次数据
                    var batch = uploadDate
                        .Skip(pageIndex * batchSize)  // 跳过已取数据
                        .Take(batchSize)              // 取当前批次
                        .ToList();                    // 物化为列表

                    var ret2 = await _cZjzy.CallRestServiceWithSoapAsync("http://192.168.1.100:8080/api/v1/vendorStock", batch);      
                    if (ret2 == "success")
                    {
                        _logger.LogInformation($"上传数据成功，数量：{batch.Count}");
                    }
                    else
                    {
                        _logger.LogError($"上传数据失败，信息：{ret2},数据：{batch[0].materialCode},数量：{batch.Count}");
                    }

                }

                _logger.LogInformation("上传数据结束");

                _logger.LogInformation("任务执行完成");                
            }
            catch(Exception ex)
            {
                _logger.LogError($"任务执行异常，信息：{ex}");
            }           
        }
    }
}
